package PartD;
import java.io.*;
import java.net.*;

public class EchoClient {

	public static void main(String args[]) {

		String message;
		String serverMessage;
		boolean sending = true;
		
		// the client input will come from standard input
		BufferedReader msgFromUser = new BufferedReader(new InputStreamReader(System.in));
		
		try {
			
			// we will be appending each echoed message to a file
			FileWriter file = new FileWriter("output.dat",true);
			
			// establish the connection and input and output streams
			Socket clientSocket = new Socket("localhost", 6789);
			DataOutputStream msgToServer = new DataOutputStream(clientSocket.getOutputStream());
			BufferedReader msgFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

			// loop until the user is finished sending
			while (sending) {
				
				// get the user message
				message = msgFromUser.readLine();

				// user can break the loop by adding ^ to the end of the line
				if (message.endsWith("^")) {
					message = message.substring(0, message.length()-1);
					sending = false;
				}

				// send the message to the server
				msgToServer.writeBytes(message + '\n');

				// read the reply from the server
				serverMessage = msgFromServer.readLine();

				// output the server response to the screen and to the file
				System.out.println("Server Says: " + serverMessage);
				file.write(serverMessage+"\n");
			}
			
			// close the file and socket
			file.close();
			clientSocket.close();

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}
